package com.yunduansing.demo.filter;

import com.alibaba.fastjson.JSON;
import com.yunduansing.demo.model.account.LoginResultModel;
import com.yunduansing.demo.model.common.CacheKeyPrefix;
import com.yunduansing.demo.model.common.ResponseModel;
import com.yunduansing.demo.service.impl.AuthUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

public class JsonLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisTemplate redisTemplate;
    private AuthUserService jwtUserService;

    public JsonLoginSuccessHandler(AuthUserService jwtUserService) {
        this.jwtUserService = jwtUserService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        var userdetails=(UserDetails)authentication.getPrincipal();
        var roles=userdetails.getAuthorities().stream().map(x->x.getAuthority().replace("ROLE_", "")).collect(Collectors.toList());
        roles.remove("null");
        String token = jwtUserService.saveUserLoginInfo(userdetails);
        response.setHeader("Authorization", "Bearer "+token);
        response.setHeader("Content-Type", "application/json");
        var stream=response.getOutputStream();
        var loginResult=new LoginResultModel();
        loginResult.setToken("Bearer "+token);
        loginResult.setCurrentAuthority(String.join(",", roles));
        loginResult.setRefreshToken(redisTemplate.opsForValue().get(CacheKeyPrefix.LOGIN_USER_TOKEN+"refresh:"+userdetails.getUsername()).toString());
        stream.println(JSON.toJSONString(ResponseModel.ok(loginResult)));
        stream.close();
    }

}
